import pygame, sys, math, random

pygame.init()

from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from Background import Background
from elight import ELight
from Money import Money
from Gate import Gates
from Blast import Blast
from HealthBar import HB
from HUD import CounterDisplay

clock = pygame.time.Clock()

green = (0,255,0)

width = 800
height = 600
size = width, height
fullscreen = 0
altFlag = False

CURSOR = (               #sized 24x24
  "           XX           ",
  "           XX           ",
  "           XX           ",
  "           XX           ",
  "         ......         ",
  "       ..oooooo..       ",
  "      .oo  XX  oo.      ",
  "     .o    XX    o.     ",
  "     .o    XX    o.     ",
  "    .o     XX     o.    ",
  "    .o     XX     o.    ",
  "XXXX.oXXXXXXXXXXXXo.XXXX",
  "XXXX.oXXXXXXXXXXXXo.XXXX",
  "    .o     XX     o.    ",
  "    .o     XX     o.    ",
  "     .o    XX    o.     ",
  "     .o    XX    o.     ",
  "      .oo  XX  oo.      ",
  "       ..oooooo..       ",
  "         ......         ",
  "           XX           ",
  "           XX           ",
  "           XX           ",
  "           XX           ",
)

cursor = pygame.cursors.compile(CURSOR)

pygame.mouse.set_cursor((24,24),(12,12),cursor[0],cursor[1])

blocksize = [50,50]
playersize = [30,50]
gridsize = [50,50]
screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0

pygame.display.set_caption('Baby Mage!!!')

blocks = pygame.sprite.Group()
elights = pygame.sprite.Group()
gates = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
projectiles = pygame.sprite.Group()
healthbars = pygame.sprite.Group()
moneys = pygame.sprite.Group()
HUDs = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()

Player.containers = (all, players)
HB.containers = (all, healthbars)
Block.containers = (all, blocks)
Money.containers = (all, moneys)
Gates.containers = (all, gates)
ELight.containers =(all, elights)
CounterDisplay.containers = (all, HUDs)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)
Blast.containers = (all, projectiles)

bg = Background("rsc/bg/mainbg.png", size)


def loadLevel(level):
	f = open(level+".lvl", 'r')
	lines = f.readlines()
	f.close()
	
	newlines = []
	
	for line in lines:
		newline = ""
		for c in line:
			if c != "\n":
				newline += c
		newlines += [newline]
	
	for y, line in enumerate(newlines):
		for x, c in enumerate(line):
			if c == "#":
				HardBlock("rsc/blocks/black.png", 
					  [(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  blocksize)
			elif c == "p":
				Block("rsc/blocks/purple.png", 
					  [(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  blocksize)
			elif c == "b":
				Block("rsc/blocks/blue.png", 
					  [(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  blocksize)
			elif c == "g":
				HardBlock("rsc/blocks/grass.png", 
					  [(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  gridsize)

			
	
	f = open(level+".tng", 'r')
	lines = f.readlines()
	f.close()
	
	newlines = []
	
	for line in lines:
		newline = ""
		for c in line:
			if c != "\n":
				newline += c
		newlines += [newline]
	
	for y, line in enumerate(newlines):
		for x, c in enumerate(line):
			if c == "@":
				player = Player([(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2],
					 playersize,
					 size)
			elif c == "e":
				Enemy("rsc/enemy/red guy.png", 
					  [(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  playersize)
			elif c == "l":
				ELight([(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/2], 
					  blocksize)
			elif c == "s":
				Gates([(x*gridsize[0])+gridsize[0]/2, (y*gridsize[1])+gridsize[1]/4], 
					  blocksize)
			elif c == "$":
				Money(5, 
					  [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
					  blocksize)
					  
	for each in all.sprites():
		each.fixLocation(player.offsetx, player.offsety)
	 
	

levels = ["rsc/levels/level1",
		  "rsc/levels/level2",
		  "rsc/levels/level3"]
def loadNextLevel(level):
	for each in all.sprites():
		each.kill()
	bg = Background("rsc/bg/mainbg.png", size)
	screen.blit(bg.image, bg.rect)
	loadLevel(levels[level])
	return level

level = 0
loadLevel(levels[level])
player1 = players.sprites()[0]
moneycounter = CounterDisplay(player1.money, (20,height - 20))
healthbar = HB(player1, (0,20))



while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		if event.type == pygame.KEYDOWN:
			if (event.key == pygame.K_RALT or event.key == pygame.K_LALT):
				altFlag = True
			if (event.key == pygame.K_RSHIFT or event.key == pygame.K_LSHIFT) and altFlag:
				if fullscreen == 0:
					fullscreen = pygame.FULLSCREEN
				else:
					fullscreen = 0
				screen = pygame.display.set_mode((width,height),fullscreen)
				pygame.display.flip()		
			if event.key == pygame.K_d:
				player1.direction("right")
			if event.key == pygame.K_a:
				player1.direction("left")
			if event.key == pygame.K_w or event.key == pygame.K_UP:
				player1.direction("jump")
			if event.key == pygame.K_RIGHT:
				player1.direction("stop right")
				Blast(player1.headingx, player1.rect.center)
			if event.key == pygame.K_LEFT:
				player1.direction("stop left")
				Blast(player1.headingx, player1.rect.center)
		if event.type == pygame.KEYUP:
			if event.key == pygame.K_d:
				player1.direction("stop right")
			#if event.key == pygame.K_SPACE:
			#	 player1.direction("stop right")
			if event.key == pygame.K_a:
				player1.direction("stop left")
			if (event.key == pygame.K_RALT or event.key == pygame.K_LALT):
				altFlag = False 
	 
	projectilesHitEnemies = pygame.sprite.groupcollide(projectiles, enemies, False, False)
	playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
	enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
	enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
	playersHitMoney = pygame.sprite.groupcollide(players, moneys, False, True)
	playersHitEnemies = pygame.sprite.groupcollide(players, enemies, False, False)
	playersHitGates = pygame.sprite.groupcollide(players, gates, False, False)
	
	font = pygame.font.Font(None, 36)
	text = font.render('PLAYER 1', 1, green)
	textpos = text.get_rect(centerx = 200)
	pygame.display.update()
	
	for player in playersHitBlocks:
		for block in playersHitBlocks[player]:
			player.collideBlock(block)
			
	for enemy in enemiesHitBlocks:
		for block in enemiesHitBlocks[enemy]:
			enemy.collideBlock(block)
			
	for enemy in enemiesHitEnemies:
		for otherEnemy in enemiesHitEnemies[enemy]:
			enemy.collideBlock(otherEnemy)
			
			
	for player in playersHitEnemies:
		for enemy in playersHitEnemies[player]:
			player.collideEnemy(enemy)
			
	for projectile in projectilesHitEnemies:
		for enemy in projectilesHitEnemies[projectile]:
			enemy.damageTaken(projectile)
			
	for player in playersHitGates:
		for gate in playersHitGates[player]:
			level = loadNextLevel(level+1)
			player1 = players.sprites()[0] 
			healthbar = HB(player1, (0,0))
			moneycounter = CounterDisplay(player1.money, (20,height - 10))
			
	for player in playersHitMoney:
		for money in playersHitMoney[player]:
			player.collideMoney(money)
			moneycounter.updateValue(player.money)
	
	all.update(size,
			   player1.speedx, 
			   player1.speedy, 
			   player1.scrollingx, 
			   player1.scrollingy,
			   player1.realx,
			   player1.realy)
	dirty = all.draw(screen)
	pygame.display.update(dirty)
	pygame.display.flip()
	clock.tick(30)
	














